global popSize weightsSize crossProb numberOfParents maxGeneration patterns solutions mutationType mutationProb nForElite strategyType tolOptimal tolContent prevBestFitness prevStdFitness tolStructure probTraining crossType anularLength probUniformCross epochsTraining;
clear;
constants;
rand('state',sum(100*clock));
AGconstants;

data = load('patternsAndSolutions.txt');
patterns = [data(:,1,:)';data(:,2,:)'];
solutions = data(:,3,:)';
tic
%genera individuos
for i = 1:popSize
    population.individuals{i} = rand(1,weightsSize).*2-1;
    population.fitness(i) = main(population.individuals{i});
end
generation = 1;
best=[];
ecm=[];
promedios=[];
diversity=[];
while (stopStrategy(strategyType, generation, population))
    parents = select(selectType,population, numberOfParents, generation);
    clear('children');
    children.individuals = {};
    children.fitness = [];
    while (length(children.individuals)<length(parents.individuals))
        firstParentIndex = randi(length(parents.individuals),1,1);
        secondParentIndex = firstParentIndex;
        while (secondParentIndex==firstParentIndex)
            secondParentIndex = randi(length(parents.individuals),1,1);
        end
        if (rand()<crossProb)
           newChildren = cross(crossType, parents.individuals{firstParentIndex}, parents.individuals{secondParentIndex});
           
           children.individuals = [children.individuals, newChildren.individuals];
           children.fitness = [children.fitness, newChildren.fitness];
        end   
    end
    
    children = mutation(mutationType, children, generation);
    children = train(children);
    
    population.individuals = [population.individuals, children.individuals];
    population.fitness = [population.fitness, children.fitness];
    population = select(replaceType,population, popSize, generation);
   
	actualBest = max(population.fitness);
	best(generation)=actualBest;
	ecm(generation)=1/actualBest;
	actualMean = mean(population.fitness);
	promedios(generation)=actualMean;
	actualDiversity = std(population.fitness)/actualMean*100;
	diversity(generation) = actualDiversity;
	sprintf('Generation: %g - Best Fitness: %g (ECM: %g) - Avg Fitness: %g - Diversity: %g', generation, actualBest, 1/actualBest, actualMean, actualDiversity)

   generation = generation + 1;
end
plot(1:generation-1,best,'r',1:generation-1,promedios,'b',1:generation-1,diversity,'g');
legend('best','average','diversity');

